/*
 * 版权所有：义乌市路比信息科技有限公司
 * 作者：kinwyb<http://www.lcfgly.com>
 * 日期：2015-8-27
 */
package lcfgly.mybatis.auto;

import java.sql.Connection;
import java.util.HashMap;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;

/**
 * 通过XML配置实用该拦截器可以简化一些基本的sql编写 自动生成单表简单的sql语句
 *
 * @author kinwyb<http://www.lcfgly.com>
 * @datetime 2015-8-27 15:52:31
 * @version 1.0
 */
@Intercepts({
    @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class AutoInterceptor extends StatementHandlerInterceptor {

    private final HashMap<String, String> autosql = new HashMap();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaStatementHandler = getMetaObject(statementHandler);
        String id = getMappedStatement(metaStatementHandler).getId();
        String sql = getBoundSQL(metaStatementHandler).getSql();
        if (null == sql || "".equals(sql.trim())) { //如果sql语句没有填写，则使用自动生成sql语句
            if (autosql.containsKey(id)) {
                sql = autosql.get(id);
            } else {
                id = getMethodName(metaStatementHandler);
                MapperMethod.ParamMap params = getParameterMap(metaStatementHandler);
                Class cs = params.get("0").getClass();
                if (id.toLowerCase().matches("^selectone.*")) {
                    sql = BuildSql.selectOne(cs, params);
                } else if (id.toLowerCase().matches("^select.*")) {
                    sql = BuildSql.select(cs, params);
                } else if (id.toLowerCase().matches("^count.*")) {
                    sql = BuildSql.count(cs, getParameterMap(metaStatementHandler));
                } else if(id.toLowerCase().matches("^insert.*")){
                    sql = BuildSql.insert(params.get("0"));
                }else if(id.toLowerCase().matches("^update.*")){
                    sql = BuildSql.update(params.get("0"));
                }else if(id.toLowerCase().matches("^delete.*")){
                    sql = BuildSql.delete(cs);
                }
                autosql.put(id, sql);
            }
            updateSql(metaStatementHandler, sql, getBoundSQL(metaStatementHandler).getParameterObject());
        }
        return invocation.proceed();
    }

}
